package com.jjh.jhwebserver.mapper;

import com.alibaba.fastjson.parser.JSONToken;
import com.jjh.jhwebserver.context.HttpServlet;
import com.jjh.jhwebserver.context.HttpServletRequest;
import com.jjh.jhwebserver.context.HttpServletResponse;
import com.jjh.jhwebserver.core.ServletContext;
import com.jjh.jhwebserver.util.FileUtils;
import com.jjh.jhwebserver.util.RegexUtil;

import java.io.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * 路径映射处理器
 * @author JJH
 */
public class UrlMappingHandler {


    private HttpServletRequest request;

    private HttpServletResponse response;

    private ServletContext context;


    public UrlMappingHandler(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
        this.context = context;
        this.request = request;
        this.response = response;
    }

    /**
     * 路径映射
     *
     * @param request requset对象
     * @return httpservlet对象
     */
    public Object urlMapping(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
        String url = request.getUrl();
        //判断静态资源
        if (RegexUtil.isStaticFiles(url)) {
            return mappingStaticResources(url, response);
        } else {
            HttpServlet[] servletes = new HttpServlet[1];
            //匹配servlet动态资源
            Map<String, Class<?>> servlets = context.getServlets();

            servlets.forEach((path, clazz) -> {
                if (url.equals(path)) {
                    //创建servlet对象
                    try {
                        HttpServlet servlet = (HttpServlet) clazz.newInstance();
                        servletes[0] = servlet;
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            return servletes[0];
        }
    }


    /**
     * 匹配静态资源
     */
    public Object mappingStaticResources(String url, HttpServletResponse response) {



        //0表示是字符串形式， 1表示是二进制文件
        int flag = 1;
        if(url.equals("/")){
           //空字符串，就去默认找index.html页面
           url = "/index.html";
           flag = 0;
        }else if (url.endsWith(".html")) {
            flag = 0;
        } else if (url.endsWith(".js")) {
            response.setHeader("Content-Type: application/javascript");
            flag = 0;
        } else if (url.endsWith(".css")) {
            response.setHeader("Content-Type: text/css");
            flag = 0;
        } else if (url.endsWith(".jpeg") || url.endsWith(".jpg")) {
            response.setHeader("Content-Type: image/jpge");
            response.setHeader("Accept-Ranges: bytes");
        } else if (url.endsWith(".webp")) {
            response.setHeader("Content-Type: image/webp");
            response.setHeader("Accept-Ranges: bytes");
        } else if (url.endsWith(".gif")) {
            response.setHeader("Content-Type: image/gif");
            response.setHeader("Accept-Ranges: bytes");
        } else if (url.endsWith(".png")) {
            response.setHeader("Content-Type: image/png");
            response.setHeader("Accept-Ranges: bytes");
        }

        List<File> files = FileUtils.getWebappsStaticFiles();

        if (flag == 0) {
            //文本格式
            BufferedReader in;
            StringBuffer sb = new StringBuffer();
            for (File file : files) {
                if (url.contains(file.getName())) {
                    try {
                        in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                        int msg;
                        while ((msg = in.read()) != -1) {
                            sb.append((char) msg);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            return sb.toString();
        }else {

          return FileUtils.getWebAppOneFile(url);
        }
    }
}


